<template lang="html">
  <div class="dashboard-page" :element-loading-text="loading.txt" v-loading="loading.status"
    v-loading.fullscreen.lock="loading.full">
  </div>
</template>

<script>
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import store from '../../store/index.js'
import router from '../../router'
import Global from '../../tools/global'
import routeConfig from '../../tools/route-config'

export default {
  data() {
    return {
      loading: {
        status: true,
        txt: '正在验证...',
        full: true,
      },
      itemName: '',
      allRoutes: null,
      routeData: [],
      is_refresh: false,
      userLevel: 0, // 0 是否为多级用户中的教育局/学校
      isMultistage: false, // 验证是否为多级版本
      root_id: 1,
      roleArr: [],
      isChangeFlag: false,
    }
  },
  created() {
    this.getTitle()
    this.getXkvideo()
  },
  mounted() {
    this.allRoutes = deep_clone(router.options.routes)
    this.checkToken()
  },
  methods: {
    // 视频库管理 root 权限
    getXkvideo() {
      const success = res => {
        this.isChangeFlag = res.data == 1 ? true : false
      }
      this.$ajax.get('/api/xkvideo/xkvideo_show', { func: { success } })
    },
    /**
     * 获取网站图标和标题
     */
    getTitle() {
      let success = (data => {
        if (!is_empty(data.data)) {
          sessionStorage.setItem('siteTitle', data.data.name)
          sessionStorage.setItem('siteIcon', (this.BASE_URL + data.data.path))
          document.title = data.data.name

          let link = document.querySelector("link[rel*='icon']") || document.createElement('link')
          link.type = 'image/x-icon'
          link.rel = 'shortcut icon'
          link.href = this.BASE_URL + data.data.path
          document.getElementsByTagName('head')[0].appendChild(link)
        }
      })
      let fail = (data => {
        this.$message.error(data.msg)
      })

      this.$ajax.get('api/setting/browser_set', { params: {}, func: { success: success, fail: fail } })
    },
    /**
     * 获取登陆状态
     */
    checkToken() {
      this.loading.status = true
      NProgress.start() // 开启Progress
      // 重写成功回调
      let success = (data => {
        if (data.data.manage === null) {
          this.$message.error('无权限登陆后台')
          setTimeout(() => {
            window.location.href = sessionStorage.getItem('host_addr')
          }, 1500)
          return false
        }
        this.routeData = data.data.manage
        // 此处为前端自定义添加路由地址，用于开发  =========== start=======
        // let newChildren = [
        //   {
        //     "id": 1126,
        //     "name": "attendance",
        //     "title": "考勤管理",
        //     "status": 1,
        //     "level": 3,
        //     "pid": 1062,
        //     "group_id": 2,
        //     "sort": 50,
        //     "display": 2,
        //     "data": "",
        //     "remark": "",
        //     "module": ""
        //   }
        // ]
        // const index = this.routeData.findIndex(system => system.id === 1062);
        // if (index !== -1) {
        //   this.routeData[index].children = this.routeData[index].children.concat(newChildren);
        // }
        // ============end=========================
        // console.log(JSON.parse(JSON.stringify(data.data)), 130)
        this.loading.txt = '验证成功...'
        this.loading.status = false
        this.userLevel = data.data.userinfo.user_level
        this.isMultistage = data.data.userinfo.is_level == true ? true : false
        this.root_id = data.data.userinfo.id
        this.roleArr = data.data.userinfo.role
        this.filterRoutes()
        this.checkIsMultilevel()
        this.getPlatformInformation()
        sessionStorage.setItem("user_level", data.data.userinfo.user_level)/*保存用户身份，教育局/学校 */
        sessionStorage.setItem("user_multistage", data.data.userinfo.is_level == true ? true : false) /*保存用户多级身份 */
        sessionStorage.setItem("user_info_str", JSON.stringify(deep_clone(data.data.userinfo)))
        sessionStorage.setItem("manage_url", data.data.manage_url)
        sessionStorage.setItem("personal_url", data.data.personal_url)
        sessionStorage.setItem("ItcJwtToken", data.data.userinfo.ItcJwtToken)
        data.data.token && sessionStorage.setItem("token", data.data.token)

        store.commit('SET_USERINFO', data.data.userinfo)
        Global.user_id = data.data.userinfo.id
        Global.role_id = data.data.userinfo.role
        //默认跳转首页
        var redirectUrl = '/'
        if (!is_empty(sessionStorage.getItem('paramString'))) {
          redirectUrl = sessionStorage.getItem('paramString')
          sessionStorage.removeItem('paramString')
        }
        console.log('http://172.16.20.171:8082/admin/login?token=' + sessionStorage.getItem('token') + '&host=' + sessionStorage.getItem('host_addr').split('://')[1] + '&CheckSchoolAppCode=' + sessionStorage.getItem('CheckSchoolAppCode'))
        console.log('http://172.16.13.176:8082/admin/login?token=' + sessionStorage.getItem('token') + '&host=' + sessionStorage.getItem('host_addr').split('://')[1] + '&CheckSchoolAppCode=' + sessionStorage.getItem('CheckSchoolAppCode'))
        this.$router.push(redirectUrl)
      })

      let fail = (data => {
        this.loading.txt = '验证失败...'

        this.$message.error(data.msg)
        //2后跳回首页
        setTimeout(() => {
          window.location.href = sessionStorage.getItem('host_addr')
        }, 2000)
      })

      this.$ajax.get('api/login/new_login', { params: {}, func: { success: success, fail: fail } })
      NProgress.done()
    },
    /**
     * 过滤路由，验证权限
     */
    filterRoutes() {
      var this_route = []
      // console.log(JSON.parse(JSON.stringify(routeConfig)), 7777)
      // console.log(sessionStorage.getItem('CheckSchoolAppCode'))

      for (var j = 0; j < routeConfig.length; j++) {
        var temp_route = {}
        //获取系统路由名字
        var sys_column = getOneColumn(this.routeData, 'name')
        var inx = sys_column.indexOf(routeConfig[j].authName)
        // console.log('---sys_column', sys_column)
        if (inx > -1) {
          temp_route.path = routeConfig[j].path
          temp_route.name = routeConfig[j].name
          temp_route.authName = routeConfig[j].authName
          temp_route.txtName = routeConfig[j].txtName
          temp_route.component = routeConfig[j].component
          temp_route.template = routeConfig[j].template
          temp_route.children = []
          if (this.isMultistage === true) {
            // 多级用户不存在 tempData 页面
            let tempArr = []
            let tempFilter = deep_clone(routeConfig[j].children)
            // let tempData = [];
            let tempData = parseInt(this.userLevel) === 0 ? ['class', 'studystatus', 'exam', 'prepare', 'count', 'leave', 'quality', 'semester', 'period'] : []
            // console.log('tempFilter---', tempFilter)
            // console.log('tempData---', tempData)
            for (let m = 0; m < routeConfig[j].children.length; m++) {
              let res = routeConfig[j].children[m]
              if (tempData.indexOf(res.path) > -1) {
                tempArr.push(m)
              }
            }

            tempArr.sort(function(a, b) {
              return b - a

            })
            tempArr.forEach(item => {
              tempFilter.splice(item, 1)
            })

            routeConfig[j].children = tempFilter
          }
          for (var k = 0; k < routeConfig[j].children.length; k++) {
            if (is_empty(this.routeData[inx].children)) {
              continue
            }

            if (routeConfig[j].name === 'system' && this.root_id !== 1) {
              routeConfig[j].children = routeConfig[j].children.filter(val1 => {
                return val1.name !== 'appset'
              })
            }

            // 多级特有的路由
            let multistage = routeConfig[j].children[k].isMultistage == true ? true : false
            if (this.isMultistage == false && this.isMultistage != multistage) {
              continue
            }

            //获取名字数组
            var module_column = getOneColumn(this.routeData[inx].children, 'name')
            let filterArray = []
            // 教育局用户没有 scheduling 审核页面
            if (this.isMultistage === true) {
              if (parseInt(this.userLevel) === 0) {
                filterArray = ['application-registration', 'comment-management', 'album-push-check', 'teacher-check', 'scheduling-apply', 'private-record', 'livePlay-review', 'textbook-management']
              } else {
                filterArray = ['album-push-check', 'comment-management', 'live-check', 'teacher-check', 'video-check']
              }
            } else {
              filterArray = ['comment-management']
            }

            // root角色可以使用的页面
            if (this.root_id !== 1) {
              // filterArray.push('stream');
              if (!this.isChangeFlag) { filterArray.push('video-library') }

              filterArray.push('version-management')
              filterArray.push('video-batch-upload')
              filterArray.push('door')
              filterArray.push('video-application')
              filterArray.push('video-live')
            }

            // 角色权限为 1、2 的用户才可以使用该页面
            filterArray.push('accommodation-list')
            if (this.roleArr.includes(1) || this.roleArr.includes(2)) {
              let roleIndex = filterArray.indexOf('accommodation-list')
              filterArray.splice(roleIndex, 1)
            }

            if (this.isChangeFlag) {
              filterArray.push('video-library')
              if (this.roleArr.includes(1) || this.roleArr.includes(2) || this.roleArr.includes(3)) {
                let roleIndex = filterArray.indexOf('video-library')
                filterArray.splice(roleIndex, 1)
              }
            }

            if (module_column.indexOf(routeConfig[j].children[k].authName) > -1) {
              // 隐藏 filterArray 页面
              let splicData = deep_clone(routeConfig[j].children[k].children)
              let keyArr = []

              for (let l = 0; l < routeConfig[j].children[k].children.length; l++) {
                let res = routeConfig[j].children[k].children[l]
                if (filterArray.indexOf(res.path) > -1) {
                  keyArr.push(l)
                }
              }
              keyArr.sort(function(a, b) {
                return b - a

              })

              keyArr.forEach(item => {
                splicData.splice(item, 1)
              })
              // console.log('splicData---', splicData)

              routeConfig[j].children[k].children = splicData

              // 是否显示多级特有页面
              let routeChild = routeConfig[j].children[k].children.filter(item => {
                if (!this.isMultistage) {
                  return item.isMultistage != true
                }
                return true
              })

              routeConfig[j].children[k].children = routeChild
              temp_route.children.push(routeConfig[j].children[k])
            }
          }
        }

        if (!is_empty(temp_route)) {
          this_route.push(temp_route)
        }
      }

      sessionStorage.setItem("route_str_back", JSON.stringify(this_route))
      this.$router.options.routes[3].children = this_route
      //生成动态路由
      this.$router.addRoutes(this.$router.options.routes)
      console.log(this.$router.options.routes, 1234)
    },
    checkIsMultilevel() { // 获取当前平台是多级还是单机 （返回1为单机 返回2为多级
      let success = res => {
        // console.log(res.data) // 值为返回值，返回1为单机 返回2为多级
        this.$g.multilevel = res.data
        let data = res.data
        let level = data == 2 ? true : false
        this.$store.commit('SET_CHECKLEVEL', level)
        sessionStorage.setItem('levelPlatform', level)
      }
      this.$ajax.get('appapi/login/check_level_platform', { func: { success } })
    },
    /**
     * 获取当前平台是教育局还是学校
     * */
    getPlatformInformation() {
      let success = res => {

        let data = res.data
        let level = data == 2 ? true : false
        this.$store.commit('SET_PLATFORM_INFORMATION', level)
      }

      this.$ajax.get('/api/newlevel/check_platform_server_type', {
        params: {
          app_code: sessionStorage.getItem('CheckSchoolAppCode')
        },
        func: { success: success }
      })
    }
  }
}
</script>
